<script setup>
import {version} from 'vue'
import {ElMessage as msg} from 'element-plus'

//npm install @element-plus/icons-vue
import {Search, Upload} from '@element-plus/icons-vue'

//导入axios库
import axios from 'axios'

//定义默认的配置参数
axios.defaults.baseURL = 'http://localhost:80/'
axios.defaults.timeout = 5000
axios.defaults.headers['token'] = 'wx123456'

//请求拦截器
axios.interceptors.request.use(
    config=>{
      config.headers['token'] = 'T------------------------123456'
      return config
    },
    error=>Promise.reject(error)
)

axios.interceptors.response.use(
    result=>{
      return result.data
    },
    error=>Promise.reject(error)
)

function a1() {
  //msg.error('hello world')
  axios({
    url: '/api/show',
    method: 'get',
    params: {id: 33, name: '李强'},
  }).then(res => {
    msg.success(JSON.stringify(res.data))
  }).catch(err => {
    msg.error('请求错误')
  })
}


function a2() {
  axios.post('/api/pp', {id: 111, name: '周勇'}).then(res => msg.success(res.data.msg)).catch(err => console.log(err))
}

function a3() {
  axios({
    url: '/api/pp2',
    method: 'post',
    params: {age: 18},
    data: 'id=99&name=王五',
    headers: {'content-type': 'application/x-www-form-urlencoded;charset=utf-8'}
  }).then(function (res) {
    msg.success(JSON.stringify(res.data))
  }).catch(error => {
    msg.error("请求失败")
  })
}

//相当于post 请求负载
function a4() {
  axios.put('/api/pt?age=88', {
    id: 66,
    name: '张三丰'
  }).then(function (res) {
    msg.success(JSON.stringify(res.data))
  }).catch(error => {
    msg.error("请求put失败")
  })
}

//相当于get params
function a5() {
  axios.delete('/api/del?age=55', {
    params: {
      id: 66,
      name: '张三丰'
    }
  }).then(function (res) {
    msg.success(JSON.stringify(res.data))
  }).catch(error => {
    msg.error("请求delete失败")
  })
}
//相当于post 请求负载数据
function a6() {
  axios({
    method: 'patch',
    url: '/api/patch',
    params:{age:18},
    data:{id:58,name:'jack'},
  }).then(function (res) {
    msg.success(JSON.stringify(res.data))
  }).catch(error => {
    msg.error("请求patch失败")
  })
}
</script>

<template>
  <h3>Hello World Vue {{ version }}</h3>
  <hr>
  <el-row>
    <el-button @click="a1">axios - get</el-button>
    <el-button type="primary" @click="a2">axios - post请求负载</el-button>
    <el-button type="primary" @click="a3">axios - post表单数据</el-button>
    <el-button type="success" @click="a4">axios - put</el-button>
    <el-button type="info" :icon="Search" @click="a5">axios - delete</el-button>
    <el-button type="warning" @click="a6">axios - patch</el-button>
    <el-button type="danger">upload file
      <el-icon class="el-icon-right">
        <Upload/>
      </el-icon>
    </el-button>
  </el-row>
</template>

<style>

</style>
